<template>
	<view class="content">
		<uni-nav-bar fixed statusBar="" title="首页" :border="false" backgroundColor="#ffcd54" color="#fff"></uni-nav-bar>
		<view class="generalize">
			<image class="money_drawing" src="/static/images/home/money-drawing.png" mode="heightFix"></image>
			<view class="generalize_box">
				<view class="fs26 mb10 text-white">本月支出(元)</view>
				<view class="fs40 fw700 text-white">￥{{ statics.expend }}</view>
			</view>
			<view class="generalize_tally dis_center_s">
				<view class="dis_center">
					<text class="fs26 text-white">收入</text>
					<text class="fs36 text-white ml10">￥{{ statics.income }}</text>
				</view>
				<view class="dis_center">
					<text class="fs26 text-white">结余</text>
					<text class="fs36 text-white ml10">￥{{ statics.spend }}</text>
				</view>
			</view>
			<view class="generalize_menus dis p20">
				<view class="fl1 dis_column_center" style="max-width: 25%;" v-for="(item, index) in menus" :key="index" @click="skipMenus(item.path)">
					<image :src="item.image" style="height: 100rpx;" mode="heightFix"></image>
					<text class="fs26 mt15">{{ item.text }}</text>
				</view>
			</view>
		</view>
		<view class="bill">
			<block v-for="item in current" :key="item.name">
				<view class="pl25">
					<view class="dis_center_s">
						<view class="dis_end">
							<text class="fs34 fw700">{{ item.name }}</text>
							<text class="fs24 text-info ml10 mr10">{{ item.week }}</text>
							<text class="fs22 text-info">{{ item.monthName }}</text>
						</view>
						<view class="dis_center pr25">
							<view class="">
								<text class="fs24">收:</text>
								<text class="fs24 income_color ml10">{{ formatTofixed(item.income) }}</text>
							</view>
							<view class="ml10">
								<text class="fs24">支:</text>
								<text class="fs24 expend_color ml10">{{ formatTofixed(item.expend) }}</text>
							</view>
						</view>
					</view>
					<uv-swipe-action>
						<uv-swipe-action-item @click="() => clickSwipe(child)" :options="options" v-for="(child, index) in item.children" :key="index">
							<view class="dis pr25">
								<view class="icon_box">
									<!-- <uni-icons :type="child.icon" custom-prefix="iconfont" :size="22" color="#fe674a"></uni-icons> -->
									<text :class="['iconfont', child.icon]" style="font-size: 44rpx;color: #fe674a;"></text>
								</view>
								<view class="fl1 dis_center_s pt25 pl25 pb25 bb1">
									<view class="">
										<view>
											<text class="fs30 fw700">{{ child.text }}</text>
											<text v-if="child.desc" class="ml10 fs24 text-info">{{ child.desc }}</text>
										</view>
										<view>
											<text class="fs24 text-info mr10">{{ child.meticulousTime }}</text>
											<text class="fs24 text-info">{{ child.payText }}</text>
										</view>
									</view>
									<text class="fs30 fw700" :class="[child.isType === '0' ? 'income_color' : 'expend_color']">{{ child.isType === '0' ? `+${child.spend}` : `-${child.spend}` }}</text>
								</view>
							</view>
						</uv-swipe-action-item>
					</uv-swipe-action>
				</view>
			</block>
		</view>
		<view class="add" @click="addTransaction">
			<uni-icons type="plusempty" :size="24" color="#fff"></uni-icons>
		</view>
	</view>
</template>

<script>
	import store from '../../store/index.js'
	import moment from 'moment'
	import { menus, weeks, payList, payTypes, icons } from '../../utils/dict-data.js'
	import { formatWeek } from '../../utils/common.js'
	const uniIdCo = uniCloud.importObject('uni-id-co')
	const uniAaccount = uniCloud.importObject('account')
	const uniTransaction = uniCloud.importObject('transaction')
	const uniUser = uniCloud.importObject('user')
	const uniSign = uniCloud.importObject('sign_in')
	export default {
		data() {
			return {
				menus,
				selectedValue: '',
				tableData: [],
				accounts: [],
				loading: false,
				options: [{ text: '删除', style: { backgroundColor: '#f56c6c' } }],
				current: [],
				page: 1,
				size: 10,
				total: 0,
				isLogin: false
			}
		},
		computed: {
			userInfo() {
				return store.state.user.userInfo
			},
			systemInfo() {
				return store.state.user.systemInfo
			},
			statics() {
				const data = this.tableData.reduce((obj, row, i) => {
					['0'].includes(row.transactionType) && (obj.income += Number(row.amount));
					['1', '2'].includes(row.transactionType) && (obj.expend += Number(row.amount))
					return obj
				}, {
					income: 0,
					expend: 0,
					spend: 0
				})
				return {
					income: data.income.toFixed(2),
					expend: data.expend.toFixed(2),
					spend: (data.income - data.expend) < 0 ? '0.00' : (data.income - data.expend).toFixed(2)
				}
			}
		},
		onLoad() {
			this.selectedValue = moment().format('YYYY-MM')
			this.getUser()
			uni.$on('showTransction', () => {
				this.getTransAll()
			})
		},
		onPullDownRefresh() {
			if(!this.loading) {
				this.loading = true
				this.getUser().catch(() => {
					this.loading = false
					uni.stopPullDownRefresh()
				})
			}
		},
		methods: {
			initSign() {
				// 签到
				uniSign.get().then(res => {
					console.log(res);
					return res.result ? null : uniSign.add({ userId: this.userInfo.uid, date: new Date().getTime(), ip: this.systemInfo.system })
				}).then(res => {
					if(res !== null) {
						uni.showToast({
							title: '签到成功',
							icon: 'none'
						})
					}
				})
			},
			getCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			getuserinfo() {
				const that = this
				uni.showModal({
					title: '温馨提示',
					content: '亲，授权获取用户头像昵称',
					success(res) {
						if(res.confirm) {
							uni.getUserProfile({
								desc: '获取用户信息用户展示',
								success(ret) {
									that.userInfo.nickName = ret.userInfo.nickName
									that.userInfo.avatar = ret.userInfo.avatarUrl
									that.login(false, (res) => {
										store.commit('user/SET_USERINFO', res)
										that.$forceUpdate()
										that.methodsAll()
									})
								},
								fail(err) {
									console.log(err);
									uni.showToast({
										title: '您拒绝了授权',
										icon: 'error',
										duration: 2000
									})
								}
							})
						}
					}
				})
			},
			getUser() {
				const that = this
				if(uni.getStorageSync('uni_id_token')) {
					uniUser.getUser().then(res => {
						if(res.code === 401) {
							console.log(res.code);
							that.login(true, (res) => {
								store.commit('user/SET_USERINFO', res)
								that.$forceUpdate()
								that.methodsAll()
							})
						} else {
							store.commit('user/SET_USERINFO', res)
							that.$forceUpdate()
							that.methodsAll()
						}
					})
				} else {
					that.getuserinfo()
				}
			},
			login(isFresh = false, cb) {
				const that = this
				if(!that.isLogin) {
					that.isLogin = true
					if(isFresh) {
						that.getCode().then(res => {
							return uniIdCo.loginByWeixin({ code: res.code })
						}).then(res => {
							return uniUser.getUser()
						}).then(res => {
							that.isLogin = false
							cb && cb(res)
						})
					} else {
						that.getCode().then(res => {
							return uniIdCo.loginByWeixin({ code: res.code })
						}).then(res => {
							return uniUser.loginSetUser({ uid: res.uid, nickName: that.userInfo.nickName, avatar: that.userInfo.avatar })
						}).then(res => {
							return uniUser.getUser()
						}).then(res => {
							that.isLogin = false
							cb && cb(res)
						})
					}
				}
			},
			/**
			 * 获取当月所有交易信息
			*/
			getTransAll() {
				uniTransaction.get({ userId: this.userInfo.uid, tallyTime: this.selectedValue }).then(res => {
					this.tableData = res.data
					this.current = this.formatTransaction(res.data, this.accounts)
				})
			},
			initAccount() {
				return new Promise((resolve, reject) => {
					uniAaccount.getAccout().then(res => {
						this.accounts = res.data.map(c => ({ text: c.accountName, value: c._id, balance: c.balance, accountType: c.accountType }))
						resolve()
					}).catch(c => reject(c))
				})
			},
			methodsAll() {
				this.initAccount().then(() => {
					return this.getTransAll()
				}).then(() => {
					return this.initSign()
				}).then(() => {
					this.loading = false
					uni.stopPullDownRefresh()
				})
			},
			addTransaction() {
				uni.navigateTo({
					url: '/pages/components/transaction/index'
				})
			},
			skipMenus(path) {
				uni.navigateTo({
					url: path
				})
			},
			clickSwipe(item) {
				const that = this
				uni.showModal({
					title: '提示',
					content: '确认删除当前项吗?',
					success(res) {
						if(res.confirm) {
							uniTransaction.delete(item._id).then(res => {
								uni.showToast({
									title: '删除成功'
								})
								that.tableData = that.tableData.filter(c => c._id !== item._id)
								that.current = that.formatTransaction(that.tableData, that.accounts)
							})
						}
					}
				})
			},
			formatTransaction(options, dicts) {
				return options.reduce((arr, row) => {
					const index = arr.findIndex(c => c.tallyTime === row.tallyTime)
					const find = icons.find(c => c.value === row.icon)
					const pay = dicts.find(c => c.value === row.accountId)
					if(index === -1) {
						const [num1, num2, num3] = row.tallyTime.split('-')
						const data = {
							name: moment().format('YYYY-MM-DD') === row.tallyTime ? '今天' : `${row.tallyTime.split('-')[2]}日`,
							week: formatWeek(moment(row.tallyTime).day()),
							tallyTime: row.tallyTime,
							monthName: `${num2}.${num1}`,
							income: row.transactionType === '0' ? Number(row.amount) : 0,
							expend: row.transactionType === '1' || row.transactionType === '2' ? Number(row.amount) : 0,
							children: [
								{
									_id: row._id,
									text: find.text,
									icon: find.value,
									meticulousTime: row.meticulousTime,
									payText: pay.text,
									isType: row.transactionType,
									spend: Number(row.amount),
									desc: row.desc
								}
							]
						}
						arr.push(data)
					} else {
						arr[index].income += row.transactionType === '0' ? Number(row.amount) : 0
						arr[index].expend += row.transactionType === '1' || row.transactionType === '2' ? Number(row.amount) : 0
						arr[index].children.push({
							_id: row._id,
							text: find.text,
							icon: find.value,
							meticulousTime: row.meticulousTime,
							isType: row.transactionType,
							payText: pay.text,
							spend: Number(row.amount),
							desc: row.desc
						})
					}
					return arr
				}, [])
			},
			formatTofixed(value) {
				if(!value) return '0'
				return value.toFixed(2)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.generalize {
		position: relative;
		height: 320rpx;
		background-color: #ffcd54;
		margin-bottom: 140rpx;
		.money_drawing {
			position: absolute;
			top: 0;
			right: 0;
			width: 100%;
			height: 100%;
		}
		.generalize_box {
			position: absolute;
			top: 60rpx;
			left: 30rpx;
			z-index: 1;
		}
		.generalize_tally {
			position: absolute;
			top: 180rpx;
			left: 30rpx;
			width: 600rpx;
			z-index: 1;
		}
		.generalize_menus {
			position: absolute;
			left: 50%;
			bottom: -110rpx;
			transform: translateX(-50%);
			width: 700rpx;
			border-radius: 12rpx;
			background-color: #fff;
			z-index: 1;
			box-shadow: 0 0 20rpx 1rpx #ccc;
			box-sizing: border-box;
		}
	}
	.bill {
		padding-bottom: 10px;
	}
	.add {
		position: fixed;
		left: 50%;
		bottom: -18rpx;
		transform: translateX(-50%);
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background-color: #ffcd54;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}
	.expend_color {
		color:  #37af6b;
	}
	.income_color {
		color: #ffcd54;
	}
	.icon_box {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #ebebeb;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
